package com.yunfeng.supercall.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.LauncherActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.widget.Toast;

import com.lin.utils.DatabaseHelperForChattingMap;
import com.lin.utils.Session;
import com.lin.utils.Session.ResultReceiver;
import com.ly.quickdev.library.utils.JsonUtils;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.BaseActivity;
import com.yunfeng.supercall.activity.ChatActivity;
import com.yunfeng.supercall.activity.InCallActivity;
import com.yunfeng.supercall.activity.LoginActivity;
import com.yunfeng.supercall.activity.MainActivity;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.bean.ChatMessageBean;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.httputils.HttpClient;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.manager.ChatMessageManager;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.SuperFriendsManager;
import com.yzx.api.UCSCall;
import com.yzx.api.UCSMessage;
import com.yzx.api.UCSService;
import com.yzx.listenerInterface.CallStateListener;
import com.yzx.listenerInterface.ConnectionListener;
import com.yzx.listenerInterface.MessageListener;
import com.yzx.listenerInterface.UcsReason;
import com.yzx.tcp.packet.UcsMessage;
import com.yzx.tcp.packet.UcsStatus;
import com.yzx.tools.FileTools;

/**
 * 云之讯通话和聊天的控制服务
 * 
 * @author 洋
 * 
 */
public class CallConnectionService extends Service implements
ConnectionListener, CallStateListener, MessageListener, Constants {

	private MyBinder mBinder;

	public class MyBinder extends Binder {

		public CallConnectionService getService() {
			return CallConnectionService.this;
		}
	}

	int cptCount = 0;

	private boolean mShouldShowNotification = true;
	private Handler mHandler = new Handler();
	// public static final String DEV_ACCOUNT = "zzzili@qq.com";
	// public static final String DEV_PASS = "zhuzili";
	/** 以下5个参数为云之讯所用的key，服务器地址等 */
	public static final String DEV_ACCOUNT = "029df7059bf2d345e0ec28aac9c7bfe6";
	public static final String DEV_PASS = "41bd092da12cc60fdf4138bb4ba6a776";
	public static final String CLIENT_ACCOUNT = "74637006196358";
	public static final String CLIENT_PASS = "9de8675c";
	public static final String SERVER_URL = "https://api.ucpaas.com";
	private HttpClient mHttpClient = new HttpClient();

	/**
	 * 设置是否接收聊天消息后需要弹通知栏
	 * 
	 * @param show
	 */
	public void setShowNotification(boolean show) {
		mShouldShowNotification = show;
	}

	public boolean isShowNotification() {
		return mShouldShowNotification;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		mBinder = new MyBinder();
		return mBinder;
	}

	SuccessReceiver mReceiver;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		//		showNotificationPersonal("收到一条语音消息","请点击查看");
		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction(UCSService.ACTION_INIT_SUCCESS);
		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		//		showNotification("title", "content");

		registerReceiver(mReceiver = new SuccessReceiver(), mFilter);
		// UCSService.connect("https://api.ucpaas.com", "8887", DEV_ACCOUNT,
		// DEV_PASS, CLIENT_ACCOUNT, CLIENT_PASS);

		// UCSService.init(getApplicationContext(), true);
		new Thread() {
			public void run() {
				UCSService.init(getApplicationContext(), true);
			};
		}.start();

		UCSService.addConnectionListener(this);
		// UCSCall.getCallStateListener().remove(this);
		UCSCall.addCallStateListener(this);
		// UCSMessage.removeMessageListener(this);
		UCSMessage.addMessageListener(this);
		UCSMessage.addMessageType(LOCATION);

		// new Thread() {
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// super.run();
		// if (!TextUtils.isEmpty(mCode)) {
		// UCSService.connect(DEV_ACCOUNT, DEV_PASS, mCode,
		// mPass);
		// }
		// }
		// }.start();
	}

	private String mCode, mPass;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		if (intent != null) {
			try {
				UserBean mUser = BaseActivity.getUser(this);
				mCode = mUser.getVo_id();
				mPass = mUser.getVo_pass();
			}catch (NullPointerException e) {

			}
			// showToast(mCode);
			new Thread() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					if (!TextUtils.isEmpty(mCode)) {
						UCSService.connect(DEV_ACCOUNT, DEV_PASS, mCode, mPass);
					}
				}
			}.start();
		}

		//		mHandler2.sendEmptyMessageDelayed(0, 1000);

		loadSuperFriend();
		flags = START_STICKY;
		return super.onStartCommand(intent, flags, startId);
	}

	List<SuperFriendsBean> mRealFriends;

	/**
	 * 加载所有的好友
	 */
	public void loadSuperFriend() {
		JSONObject json = BaseActivity.getBaseParams(this);
		try {
			json.put("i_pagenum", 0);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_GET_FRIEND_LIST, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				mRealFriends = JsonUtils.parseList(data, SuperFriendsBean.class);
				// showToast(data);
				Collections.sort(mRealFriends);
				ManagerFactory.createManager(SuperFriendsBean.class).saveList(
						mRealFriends);
			}

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub
			}
		});
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mReceiver);
		UCSMessage.removeMessageListener(this);
		UCSCall.getCallStateListener().remove(this);
		UCSService.getConnectionListener().remove(this);
		UCSService.uninit();
		// UCSService.uninit(getApplicationContext());
		// android.os.Process.killProcess(android.os.Process.myPid());
	}

	public void showToast(final String toast) {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Toast.makeText(CallConnectionService.this, toast,
						Toast.LENGTH_LONG).show();
			}
		});

	}

	@Override
	public void onConnectionFailed(UcsReason reason) {
		// TODO Auto-generated method stub
		// showToast(reason.getMsg());
		Log.i("tag", "faile");
		cptCount ++;
		//		if(cptCount < 2) {		
		//			try {
		//				UserBean mUser = BaseActivity.getUser(this);
		//				mCode = mUser.getVo_id();
		//				mPass = mUser.getVo_pass();
		//			} catch(NullPointerException e) {
		//
		//			}
		//			new Thread() {  //登录
		//				@Override
		//				public void run() {
		//					// TODO Auto-generated method stub
		//					super.run();
		//					if (!TextUtils.isEmpty(mCode)) {
		//						UCSService.connect(DEV_ACCOUNT, DEV_PASS, mCode, mPass);
		//					}
		//				}
		//			}.start();
		//			return;
		//		}

		/*if( reason.getReason() == 300207) {		
					try {
						UserBean mUser = BaseActivity.getUser(this);
						mCode = mUser.getVo_id();
						mPass = mUser.getVo_pass();
					} catch(NullPointerException e) {

					}
					new Thread() {  //登录
						@Override
						public void run() {
							// TODO Auto-generated method stub
							super.run();
							if (!TextUtils.isEmpty(mCode)) {
								UCSService.connect(DEV_ACCOUNT, DEV_PASS, mCode, mPass);
							}
						}
					}.start();
					return;
				}*/
		/*|| reason.getReason() == 300505 */
		if (reason.getReason() == 300207 ) {
			startActivity(new Intent(CallConnectionService.this,
					LoginActivity.class).addFlags(
							Intent.FLAG_ACTIVITY_NEW_TASK
							| Intent.FLAG_ACTIVITY_CLEAR_TASK).putExtra(
									"reason", getString(R.string.account_logined_at_somewhere)));
			//			stopSelf();
		} else {
			sendBroadcast(new Intent(ACTION_CONNECTION_FAILED));
		}
	}

	@Override
	public void onConnectionSuccessful() {
		// TODO Auto-generated method stub
		// showToast("成功");
		// showToast("连接聊天服务器成功");
		Log.i("tag", "success");
		cptCount = 0;
		sendBroadcast(new Intent(ACTION_CONNECTION_SUCCESS));
		sendBroadcast(new Intent(ACTION_CONNECTION_SUCCESS2));
	}

	@Override
	public void onAlerting(String arg0) {
		// TODO Auto-generated method stub
		sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra("state",
				UCSCall.CALL_VOIP_RINGING_180));
	}

	@Override
	public void onAnswer(String arg0) {
		// TODO Auto-generated method stub
		sendBroadcast(new Intent(Constants.ACTION_ANSWER));
	}

	@Override
	public void onCallBackSuccess() {
		// TODO Auto-generated method stub

	}

	// @Override
	// public void onConferenceModeConvert(String arg0) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onConferenceState(String arg0, List arg1) {
	// // TODO Auto-generated method stub
	//
	// }

	/**
	 * 云之讯在此方法中回调状态码
	 */
	@Override
	public void onDialFailed(String arg0, UcsReason arg1) {
		// TODO Auto-generated method stub
		voipSwitch(arg1);
	}

	@Override
	public void onHangUp(String arg0, UcsReason arg1) {
		// TODO Auto-generated method stub
		UCSCall.stopCallRinging();
		voipSwitch(arg1);
	}

	// @Override
	// public void onIncomingCall(String callId, String callType,
	// String callerNumber) {
	// // TODO Auto-generated method stub
	// Intent intent = new Intent();
	// intent.putExtra("number", callerNumber);
	// intent.setClass(this, InCallActivity.class);
	// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	// startActivity(intent);
	// }

	@Override
	public void onDownloadAttachedProgress(String arg0, String arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub

	}

	public void showNotification(ChatMessageBean chatMessage, SuperFriendsBean friends) {
		if (!mShouldShowNotification) {
			return;
		}
		if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
				"newmsg", true)) {

			Builder mBuilder = new Builder(this);
			Bitmap bitmap = FinalBitmap.create(this).getBitmapFromCache(
					AppContext.IMG_TOP + friends.getPhoto());
			if (bitmap == null) {
				bitmap = AppContext.BITMAP;
			}
			mBuilder.setLargeIcon(bitmap);
			mBuilder.setContentTitle(getString(R.string.someone_send_a_message,
					friends.getReal_name()));
			String content = "";
			switch (chatMessage.getChatType()) {

			case ChatMessageBean.TYPE_LOCATION:
				content = getString(R.string.msg_type_location);
				break;
			case ChatMessageBean.TYPE_PIC:
				content = getString(R.string.msg_type_img);
				break;
			case ChatMessageBean.TYPE_VOICE:
				content = getString(R.string.msg_type_voice);
				break;
			default:
			case ChatMessageBean.TYPE_TEXT:
				content = chatMessage.getContent();
				break;

			}
			mBuilder.setContentText(content);
			mBuilder.setDefaults(Notification.DEFAULT_ALL);
			mBuilder.setAutoCancel(true);
			Notification mNotification = mBuilder.build();
			// Vibrator mVibrator =(Vibrator)
			// getSystemService(VIBRATOR_SERVICE);
			// Vibrator mVibrator = (Vibrator)
			// getSystemService(VIBRATOR_SERVICE);
			// mVibrator.vibrate(new long[] { 0, 300, 300, 300 }, -1);
			// mNotification.vibrate = ;
			Intent intent = new Intent(this, MainActivity.class);
			intent.setAction(FROM_CHAT_NOTIFICATION);
			intent.putExtra(
					Constants.KEY_DATA, friends).addFlags(
							Intent.FLAG_ACTIVITY_SINGLE_TOP);
			mNotification.contentIntent = PendingIntent.getActivity(
					this,
					300,
					intent,
					PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_CANCEL_CURRENT);
			NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			mNotification.icon = R.drawable.ic_launcher;

			manager.notify(300, mNotification);
		}
	}

	@Override
	public void onReceiveUcsMessage(UcsReason arg0, UcsMessage arg1) {
		// TODO Auto-generated method stub
		ChatMessageBean chatMessage = new ChatMessageBean();
		chatMessage.setContent(arg1.getMsg());
		chatMessage.setSendFromMySelf(false);
		chatMessage.setReceiveTime(System.currentTimeMillis());
		chatMessage.setMsgFrom(arg1.getFormuid());
		chatMessage.setMsgTo(BaseActivity.getUser(this).getVo_id());


		DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(getApplicationContext(), "db", 2);
		SuperFriendsBean mSuperFriendsBean = mDatabaseHelperForChattingMap.getSuperFriendsBeanByVoId(arg1.getFormuid());
		if(mDatabaseHelperForChattingMap != null) {
			mDatabaseHelperForChattingMap.close();
			mDatabaseHelperForChattingMap = null;
		}

		if(TextUtils.isEmpty(mSuperFriendsBean.getPhone())) {
			new Thread(new RunnableSearchByVoId(arg1.getFormuid())).start();
		}

		switch (arg1.getExtra_mime()) {
		case UCSMessage.VOICE:
			chatMessage.setChatType(ChatMessageBean.TYPE_VOICE);
			//			showNotificationPersonal("语音" + chatMessage.getMsgId() + "," + chatMessage.getId() , chatMessage.getContent());
			//			showNotificationPersonal("收到一条语音消息","请点击查看");
			downloadVoiceAndSendMsg(chatMessage, arg1);
			return;
		case UCSMessage.PIC:
			chatMessage.setChatType(ChatMessageBean.TYPE_PIC);
			//			showNotificationPersonal("图片" + chatMessage.getMsgId() + "," + chatMessage.getId() , chatMessage.getContent());
			//			showNotificationPersonal("收到一条图片消息","请点击查看");
			break;
		case LOCATION:
			chatMessage.setChatType(ChatMessageBean.TYPE_LOCATION);
			//			showNotificationPersonal("地址分享" + chatMessage.getMsgId() + "," + chatMessage.getId() , chatMessage.getContent());
			//			showNotificationPersonal("收到一条地址分享","请点击查看");
			break;
		default:
			chatMessage.setChatType(ChatMessageBean.TYPE_TEXT);
			//			showNotificationPersonal("文本" + chatMessage.getMsgId() + "," + chatMessage.getId() , chatMessage.getContent());
			//			showNotificationPersonal(chatMessage.getContent(),"请点击查看");
			break;
		}

		/*		DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(getApplicationContext(), "db", 2);
		mDatabaseHelperForChattingMap.getSuperFriendsBean();
		mDatabaseHelperForChattingMap.close();
		 */		
		//当收到信息时 向服务器询问是否有这人

		SuperFriendsManager manager = (SuperFriendsManager) ManagerFactory
				.createManager(SuperFriendsBean.class);
		//通过void搜索对应的用户
		mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(getApplicationContext(), "db", 2);

		SuperFriendsBean su = mDatabaseHelperForChattingMap.getSuperFriendsBeanByVoId(arg1.getFormuid());
		if(mDatabaseHelperForChattingMap != null) {
			mDatabaseHelperForChattingMap.close();
		}
		//		SuperFriendsBean su = manager
		//				.findSuperFriendsByYZXNumber(arg1.getFormuid());
		ChatMessageManager.getInstance(this).putMessages(su, chatMessage);
		showNotification(chatMessage, su);
		sendBroadcast(new Intent(Constants.ACTION_RECEIVE_MSG).putExtra(
				Constants.KEY_DATA, chatMessage));
	}

	private class RunnableSearchByVoId implements Runnable {
		String vo_id;

		public RunnableSearchByVoId(String vo_id) {
			super();
			this.vo_id = vo_id;
		}



		@Override
		public void run() {
			// TODO Auto-generated method stub
			Session mSession = Session.getSession();
			mSession.getVoidObject(getApplicationContext(), mSession.getmUserBean().getUserid() + "", vo_id, new ResultReceiver<SuperFriendsBean>() {

				@Override
				public void onResult(boolean last, SuperFriendsBean data) {
					// TODO Auto-generated method stub
					try {




						DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(getApplicationContext(), "db", 2);
						mDatabaseHelperForChattingMap.insertSuperFrined(data);
						if(mDatabaseHelperForChattingMap != null) {
							mDatabaseHelperForChattingMap.close();
							mDatabaseHelperForChattingMap = null;
						}
					} catch(Exception e) {
						e.printStackTrace();
					} finally {
						sendBroadcast(new Intent(Constants.ACTION_RECEIVE_MSG));
					}

				}

			});
		}

	}



	private Map<String, Boolean> mHasDownLoaded = new HashMap<String, Boolean>();

	private void downloadVoiceAndSendMsg(final ChatMessageBean chatMessage,
			final UcsMessage ucsMessage) {
		final String localPath = FileTools.createAudioFileName(ucsMessage
				.getFormuid());
		UCSMessage.downloadAttached(ucsMessage.getMsg(), localPath,
				ucsMessage.getMsgId(), new MessageListener() {

			@Override
			public void onUserState(ArrayList arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSendUcsMessage(UcsReason arg0, UcsMessage arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSendFileProgress(int arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onReceiveUcsMessage(UcsReason arg0,
					UcsMessage arg1) {
				// TODO Auto-generated method stub

			}

			/**
			 * 这个方法会被调用3次，好奇怪
			 * 
			 */
			@Override
			public void onDownloadAttachedProgress(String msgId,
					String filePaht, final int sizeProgrss,
					final int currentProgress) {
				// TODO Auto-generated method stub

				if (currentProgress >= sizeProgrss) {
					if (mHasDownLoaded.get(msgId) != null
							&& mHasDownLoaded.get(msgId) ) {
						return;
					}
					if(!msgId.contains("amr")) return;
					try {
						chatMessage.setVoiceLenth(UCSMessage
								.getVoiceDuration(localPath) / 1000);
						chatMessage.setContent(localPath);
						SuperFriendsManager manager = (SuperFriendsManager) ManagerFactory
								.createManager(SuperFriendsBean.class);
						SuperFriendsBean su = manager
								.findSuperFriendsByYZXNumber(ucsMessage
										.getFormuid());
						ChatMessageManager.getInstance(
								CallConnectionService.this).putMessages(su,
										chatMessage);
						sendBroadcast(new Intent(
								Constants.ACTION_RECEIVE_MSG).putExtra(
										Constants.KEY_DATA, chatMessage));
						UCSMessage.removeMessageListener(this);
						mHasDownLoaded.put(msgId, true);
						showNotification(chatMessage, su);
					} catch(NullPointerException e) {

					}
				}
			}
		});

	}

	@Override
	public void onSendFileProgress(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSendUcsMessage(UcsReason arg0, UcsMessage arg1) {
		// TODO Auto-generated method stub
		// try {
		// if (BuildConfig.DEBUG) {
		// showToast(arg0.getReason() + arg0.getMsg());
		// }
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// }
	}

	public static Map<String, UcsStatus> mUserStateMap = new HashMap<String, UcsStatus>();

	@Override
	public void onUserState(ArrayList arg0) {
		// TODO Auto-generated method stub
		mUserStateMap.clear();
		for (int i = 0; i < arg0.size(); i++) {
			UcsStatus status = (UcsStatus) arg0.get(i);
			// System.out.println("CallConnectionService.onUserState()"
			// + status.getUid());
			mUserStateMap.put(status.getUid(), status);
		}
		sendBroadcast(new Intent(ACTION_QUERY_USER_STATE));
	}

	/**
	 * 根据状态码发送广播
	 * 
	 * @param reason
	 */
	private void voipSwitch(UcsReason reason) {
		switch (reason.getReason()) {
		case 300210:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_ERROR));
			break;
		case 300211:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_NOT_ENOUGH_BALANCE));
			break;
		case 300212:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_BUSY));
			break;
		case 300213:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_REFUSAL));
			break;
		case 300214:
		case 300215:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_NUMBER_ERROR));
			break;
		case 300216:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_ACCOUNT_FROZEN));
			break;
		case 300217:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_REJECT_ACCOUNT_FROZEN));
			break;
		case 300218:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_ACCOUNT_EXPIRED));
			break;
		case 300219:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_CALLYOURSELF));
			break;
		case 300220:
		case 300224:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_NETWORK_TIMEOUT));
			break;
		case 300221:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_NOT_ANSWER));
			break;
		case 300222:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_TRYING_183));
			break;
		case 300223:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_SESSION_EXPIRATION));
			break;
		case 300225:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.HUNGUP_MYSELF));
			break;
		case 300226:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.HUNGUP_OTHER));
			break;
		case 300247:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VOIP_RINGING_180));
			break;
		case 300248:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.HUNGUP_MYSELF_REFUSAL));
			break;
		case 300249:
			sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
					"state", UCSCall.CALL_VIDEO_DOES_NOT_SUPPORT));

			break;
		default:
			if (reason.getReason() >= 10000 && reason.getReason() <= 20000) {
			} else if (reason.getReason() >= 300233
					&& reason.getReason() <= 300250) {
				sendBroadcast(new Intent(Constants.ACTION_DIAL_STATE).putExtra(
						"state", reason.getReason()));
			}
			break;
		}
	}

	/** 连接成功的监听器 */
	public class SuccessReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent != null
					&& UCSService.ACTION_INIT_SUCCESS
					.equals(intent.getAction())) {
				// showToast("初始化连接成功");
				// new Thread() {
				// @Override
				// public void run() {
				// // TODO Auto-generated method stub
				// super.run();
				// if (!TextUtils.isEmpty(mCode)) {
				new Thread() {
					public void run() {
						UCSService.connect(DEV_ACCOUNT, DEV_PASS, mCode, mPass);
					};
				}.start();

				// }
				// }
				// }.start();

			}
		}
	}

	@Override
	public void onConferenceModeConvert(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onConferenceState(String arg0, ArrayList arg1) {
		// TODO Auto-generated method stub

	}

	/**
	 * 云之讯的接口，当来电时
	 */
	@Override
	public void onIncomingCall(String callId, String callType,
			String callerNumber, String nickName, String userdata) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		intent.putExtra("number", callerNumber);
		intent.setClass(this, InCallActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}



	private NotificationManager mNM;

	private void showNotificationPersonal(String title, String content) {


		//		Intent[] mIntents = new Intent[1];
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		Intent mIntents = new Intent(this, MainActivity.class);
		/*		if (currentapiVersion > 10) {
			mIntents[0] = new Intent(this, LauncherActivity.class);


		}*/
		mIntents.setAction(FROM_CHAT_NOTIFICATION);
		mIntents.putExtra(
				Constants.KEY_DATA, new SuperFriendsBean()).addFlags(
						Intent.FLAG_ACTIVITY_SINGLE_TOP);

		PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, mIntents, PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_CANCEL_CURRENT);
		Notification notification = null;
		try {
			notification = new NotificationCompat.Builder(
					getApplicationContext())
			.setContentTitle(title)
			.setContentIntent(pendingIntent).setContentText(content + "")
			.setSmallIcon(R.drawable.ic_launcher)
			.setWhen(System.currentTimeMillis()).setAutoCancel(true)
			.build();

			Intent intent = new Intent(this, MainActivity.class);
			intent.setAction(FROM_CHAT_NOTIFICATION);
			intent.putExtra(
					Constants.KEY_DATA, new SuperFriendsBean()).addFlags(
							Intent.FLAG_ACTIVITY_SINGLE_TOP);

			notification.contentIntent = PendingIntent.getActivity(
					this,
					300,
					intent,
					PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_CANCEL_CURRENT);

		} catch (Exception e) {
			notification = new NotificationCompat.Builder(
					getApplicationContext())
			.setContentTitle(title).setContentIntent(pendingIntent)
			.setContentText(content + "")
			.setSmallIcon(R.drawable.ic_launcher)
			.setWhen(System.currentTimeMillis()).setAutoCancel(true)
			.getNotification();

			Intent intent = new Intent(this, MainActivity.class);
			intent.setAction(FROM_CHAT_NOTIFICATION);
			intent.putExtra(
					Constants.KEY_DATA, new SuperFriendsBean()).addFlags(
							Intent.FLAG_ACTIVITY_SINGLE_TOP);

			notification.contentIntent = PendingIntent.getActivity(
					this,
					300,
					intent,
					PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_CANCEL_CURRENT);
		}

		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		notification.flags |= Notification.DEFAULT_VIBRATE;

		notification.defaults=Notification.DEFAULT_SOUND;
		// Send the notification.
		// We use a string id because it is a unique number. We use it later to
		// cancel.
		try {
			mNM.notify("service_created", 10, notification);
			AcquireWakeLock(3000);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private PowerManager.WakeLock m_wakeLockObj = null;
	public void AcquireWakeLock(long milltime) {
		if (m_wakeLockObj == null) {
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			m_wakeLockObj = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
					| PowerManager.ACQUIRE_CAUSES_WAKEUP
					| PowerManager.ON_AFTER_RELEASE, "tag");


			m_wakeLockObj.acquire(milltime);
		}
	}


	public void ReleaseWakeLock() {
		Log.i("tag", " ---------------------------------取消点亮");
		if (m_wakeLockObj != null && m_wakeLockObj.isHeld()) {
			m_wakeLockObj.release();
			m_wakeLockObj = null;
		}
	}

	int cpt = 0;

	Handler mHandler2 = new Handler() {


		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			try {

				UserBean mUser = BaseActivity.getUser(CallConnectionService.this);
				mCode = mUser.getVo_id();
				mPass = mUser.getVo_pass();
				Log.i("tag", "code:" + mCode + ", pass:" + mPass);
				try {
					cpt ++;
					showNotificationPersonal(cpt + "", cpt + "", 2);
					Thread.sleep(1000);
					mHandler2.sendEmptyMessageDelayed(0, 1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch(NullPointerException e) {

			}
		}

	};

	private void showNotificationPersonal(String title, String content, int id) {


		//		Intent[] mIntents = new Intent[1];
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		Intent mIntents = new Intent(this, MainActivity.class);
		mIntents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
		/*		if (currentapiVersion > 10) {
				mIntents[0] = new Intent(this, LauncherActivity.class);


			}*/

		mIntents.setAction(FROM_CHAT_NOTIFICATION);
		PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, mIntents, PendingIntent.FLAG_CANCEL_CURRENT);
		Notification notification = null;
		try {

			notification = new NotificationCompat.Builder(
					getApplicationContext())
			.setContentTitle(title)
			.setContentIntent(pendingIntent).setContentText(content + "")
			.setSmallIcon(R.drawable.ic_launcher)

			.setWhen(System.currentTimeMillis()).setAutoCancel(true)
			.build();

		} catch (Exception e) {
			notification = new NotificationCompat.Builder(
					getApplicationContext())
			.setContentTitle(title).setContentIntent(pendingIntent)
			.setContentText(content + "")
			.setSmallIcon(R.drawable.ic_launcher)
			.setWhen(System.currentTimeMillis()).setAutoCancel(true)
			.getNotification();
		}

		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		notification.flags |= Notification.DEFAULT_VIBRATE;

		//		notification.defaults=Notification.DEFAULT_SOUND;
		// Send the notification.
		// We use a string id because it is a unique number. We use it later to
		// cancel.
		try {
			mNM.notify("service_created", id, notification);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onChatRoomIncomingCall(String arg0, String arg1, String arg2,
			String arg3, String arg4) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onChatRoomModeConvert(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onChatRoomState(String arg0, ArrayList arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDTMF(int arg0) {
		// TODO Auto-generated method stub

	}
}
